import UIKit

class WBMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupChildControllers()
        setupComposeButton()
    }
    
    // 支持横屏幕
    // 如果要播放视频，采用modal
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        // 屏幕树立，控制设备方向
        return .portrait
    }

    
    // 设置监听方法
    // @objc private 保证方法私有，当前对象才能访问，并且 运行时通过 OC 的消息机制访问
    @objc private func composeStatus()  {
        print("添加小红书")
    }

    // 私有控件
    private lazy var composeButton: UIButton = {
        let button = UIButton(type: .system) // 创建按钮，使用系统样式
        if let image = UIImage(named: "home_btn") {
            button.setImage(image.withRenderingMode(.alwaysOriginal), for: .normal) // 设置按钮图片
        }
        button.backgroundColor = .clear // 设置背景颜色为透明
        button.layer.cornerRadius = 25 // 设置按钮圆角，尺寸应为宽高的一半
        button.translatesAutoresizingMaskIntoConstraints = false // 允许使用 Auto Layout
//         button.addTarget(self, action: #selector(composeButtonTapped), for: .touchUpInside) // 添加点击事件处理器
        return button
    }()

    // 设置所有子控制器
    private func setupChildControllers() {
        let array = [
            ["clsName": "WBHomeViewController", "title": "首页", "imageName": "record_ip_protein"],
            // 中间的plus按钮
            ["clsName": "UIViewController"],
            ["clsName": "WBMessageViewController", "title": "消息", "imageName": "record_ip_cabs"]
        ]
        var arrayM = [UIViewController]()
        for dict in array {
            arrayM.append(controllers(dict: dict))
        }
        viewControllers = arrayM
    }
    
    // 使用字典创建一个子控制器
    // dict:[clsName,title,imageName]
    // 获取字典内容
    private func controllers(dict: [String: String]) -> UIViewController {
        guard let clsName = dict["clsName"],
              let title = dict["title"],
              let imageName = dict["imageName"],
              let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? UIViewController.Type
        else {
            return UIViewController()
        }
        
        // 创建 vc，视图控制器
        let vc = cls.init()
        vc.title = title
        // 设置图片大小
        let image = UIImage(named: imageName)
        let resizedImage = resizeImage(image: image ?? UIImage(), targetSize: CGSize(width: 25, height: 25))
        vc.tabBarItem.image = resizedImage.withRenderingMode(.alwaysOriginal)

        // 设置选中图片
        let selectedImage = UIImage(named: imageName + "_selected")
        let resizedSelectedImage = resizeImage(image: selectedImage ?? UIImage(), targetSize: CGSize(width: 25, height: 25))
        vc.tabBarItem.selectedImage = resizedSelectedImage.withRenderingMode(.alwaysOriginal)
        
        // 设置字体
        vc.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.orange], for: .highlighted)
        
        // 初始化导航控制器
        let nav = WBNavigationViewController(rootViewController: vc)
        return nav
    }
    
    private func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
        let size = image.size

        let widthRatio  = targetSize.width  / size.width
        let heightRatio = targetSize.height / size.height

        // 确定新的图片大小
        let newSize = CGSize(width: size.width * widthRatio, height: size.height * heightRatio)

        // 开始绘制新的图片
        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
        image.draw(in: CGRect(origin: .zero, size: newSize))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage ?? image
    }
    
    // 设置 composeButton
    private func setupComposeButton() {
        tabBar.addSubview(composeButton)
        
        // 添加约束
        NSLayoutConstraint.activate([
            composeButton.centerXAnchor.constraint(equalTo: tabBar.centerXAnchor),
            composeButton.bottomAnchor.constraint(equalTo: tabBar.bottomAnchor, constant: 10),
            composeButton.widthAnchor.constraint(equalToConstant: 150),
            composeButton.heightAnchor.constraint(equalToConstant: 150)
        ])
        
        // 设置监听方法，点击事件
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
}
